﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
//using Mono.Data.Sqlite;
using System.Linq;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Point : MonoBehaviour, IPointerClickHandler
{

    //private int line_id; 
    //private SQLiteHelper sql;
    //声音
    public AudioClip success;
    public AudioClip fail;

    //连线网络
    public string[][] LineMap =  {
       new string[]{"ebox1_p1","sw1_p2","line1"},
       new string[]{"sw1_p1","sw2_p3","line2" },
       new string[]{"sw1_p3","sw2_p1","line3"},
       new string[]{"sw2_p2","lamp1_p1","line4" },
       new string[]{"ebox1_p2","lamp1_p2","line5"}
    };

    public Line_model Line;  //线模型
    public Yj_model yj;        //元件模型  
    public GameObject flyline; //飞线 

    Text czts; //连线提示

    void Start()
    {
        //获得元件模型参数
        GameObject go =transform.parent.parent.gameObject;
        yj = (Yj_model)go.GetComponent(typeof(Yj_model));
        //获得导线模型参数
        GameObject root = GameObject.Find("root");
        GameObject go1 = root.transform.Find("line").gameObject;
        Line = (Line_model)go1.GetComponent(typeof(Line_model));
        flyline = root.transform.Find("flyline").gameObject;
        //添加声音clip
        success = (AudioClip)Resources.Load("success", typeof(AudioClip));
        fail = (AudioClip)Resources.Load("fail", typeof(AudioClip));
        //获得连线提示
        czts = GameObject.Find("czts").GetComponent<Text>();             
    }


    // Update is called once per frame
    void Update()
    {

    }

  
    //点击联线
    public void OnPointerClick(PointerEventData eventData)
    {
        //Debug.Log("point:"+this.name);
        /*        sql = new SQLiteHelper("data source=Assets/esvt.db");
                string PointName = this.name;
                string queryStr = "SELECT * FROM circuit WHERE point1= '"+this.name+"'";
                SqliteDataReader read=sql.ExecuteQuery(queryStr);
                while (read.Read())
                {
                    Debug.Log(read.GetString(3));
                    Debug.Log(read.GetString(read.GetOrdinal("point1")));
                    Debug.Log(read.GetString(read.GetOrdinal("line")));
                    Debug.Log(read.GetInt16(read.GetOrdinal("id")));
                }
                sql.CloseConnection();*/
        

        
        if (Init.startPoint == "")
        {
            Init.startPoint = this.name;
            //Debug.Log("1start:" + Init.startPoint + "end:" + Init.endPoint);
            Init.startFly = this.transform.position;
            Init.isFly = 1;
            flyline.SetActive(true);
            
        }
        else if (Init.startPoint != ""&&Init.startPoint!=this.name&& Init.endPoint == "")
        {
            Init.endPoint = this.name;

            Debug.Log("2start:" + Init.startPoint + "end:" + Init.endPoint);
            Init.isFly = 0;
            flyline.SetActive(false);
            flyline.transform.position = new Vector3(0, 0, 0);
        }
        //相机回原点
        StartCoroutine(MoveToPosition());
        

        if (Init.startPoint != "" && Init.endPoint != "")
        {
            Debug.Log("3start:"+Init.startPoint+"end:"+Init.endPoint);

            for(int i=0; i < 5; i++)
            {
                if (Line.line[i].activeSelf == false)
                {
                    if (LineMap[i].Contains(Init.startPoint) && LineMap[i].Contains(Init.endPoint))
                    {
                        Line.line[i].SetActive(true);
                        AudioSource.PlayClipAtPoint(success, this.transform.position);
                        czts.text = "连接正确，太棒了！";              
                        Init.shanIndex = i + 1;
                    }
                    else
                    {
                        AudioSource.PlayClipAtPoint(fail, this.transform.position);
                        if(SceneManager.GetActiveScene().name== "04_anzhuang")
                        {
                            czts.text = "连接错误，请将鼠标移动到原理图连线处，根据操作提示重试，加油哦！";
                        }else if(SceneManager.GetActiveScene().name == "05_exam")
                        {
                            czts.text = "连接错误，请重试！";
                            Init.errNum++;
                            //操作错误一次，模拟考核成绩-5
                            if (Init.score >=60)
                            {
                                Init.score -= 5*Init.errNum;
                            }
                            else
                            {
                                czts.text = "太遗憾了，你操作的错误次数过多，请重新来过！";
                                GameObject.Find("UI").transform.Find("mask").gameObject.SetActive(true);
                            }
                                                            
                        }
                        
                    }                  
                    break;
                }
            }
            Init.startPoint = "";
            Init.endPoint = "";         
            Init.isFly = 0;
        }
    }
    
    //摄像机回原点协程
    IEnumerator MoveToPosition()
    {
        GameObject maincam = GameObject.Find("Main Camera");
        Vector3 target = Init.camPos0;
        maincam.transform.rotation = Quaternion.Euler(0, 0, 0); //设置摄像机rotation回原点
        while (maincam.transform.position != target)
        {

            maincam.transform.position = Vector3.MoveTowards(maincam.transform.position, target, 10 * Time.deltaTime);
            yield return 0;
        }
        yj.yja.SetActive(true);
        transform.parent.gameObject.SetActive(false);

    }

    void DrawLine(Vector3 start,Vector3 end)
    {
        GameObject obj = new GameObject();
        LineRenderer lineRenderer;
        lineRenderer = obj.AddComponent<LineRenderer>();
        lineRenderer.useWorldSpace = false;//是否使用世界坐标，true的话，自身坐标将被忽略。
        //lineRenderer.material = new Material(Shader.Find("Particles/Additive"));
        lineRenderer.startColor=Color.white;//设置颜色，一个是起始和终止颜色。
        lineRenderer.positionCount=1;//设置线段数量，可以根据需求来动态改变，灵活改变。     
        lineRenderer.SetPosition(0, start);
        lineRenderer.SetPosition(1, end);
    }
    //SQLite 示例
   /*  void SqliteDemo()
    {
        Debug.Log("SQLlite 测试");
        //创建名为sqlite4unity的数据库
        sql = new SQLiteHelper("data source=Assets/esvt.db");
       
                //创建名为table1的数据表
                sql.CreateTable("table1", new string[] { "ID", "Name", "Age", "Email" }, new string[] { "INTEGER", "TEXT", "INTEGER", "TEXT" });

                //插入两条数据
                sql.InsertValues("table1", new string[] { "'1'", "'张三'", "'22'", "'Zhang3@163.com'" });
                sql.InsertValues("table1", new string[] { "'2'", "'李四'", "'25'", "'Li4@163.com'" });

                //更新数据，将Name="张三"的记录中的Name改为"Zhang3"
                sql.UpdateValues("table1", new string[] { "Name" }, new string[] { "'Zhang3'" }, "Name", "=", "'张三'");

                //插入3条数据
                sql.InsertValues("table1", new string[] { "3", "'王五'", "25", "'Wang5@163.com'" });
                sql.InsertValues("table1", new string[] { "4", "'王五'", "26", "'Wang5@163.com'" });
                sql.InsertValues("table1", new string[] { "5", "'王五'", "27", "'Wang5@163.com'" });

                //删除Name="王五"且Age=26的记录,DeleteValuesOR方法类似
                sql.DeleteValuesAND("table1", new string[] { "Name", "Age" }, new string[] { "=", "=" }, new string[] { "'王五'", "'26'" });

                //读取整张表
                SqliteDataReader reader = sql.ReadFullTable("table1");
                while (reader.Read())
                {
                    //读取ID
                    Debug.Log(reader.GetInt32(reader.GetOrdinal("ID")));
                    //读取Name
                    Debug.Log(reader.GetString(reader.GetOrdinal("Name")));
                    //读取Age
                    Debug.Log(reader.GetInt32(reader.GetOrdinal("Age")));
                    //读取Email
                    Debug.Log(reader.GetString(reader.GetOrdinal("Email")));
                }

                //读取数据表中Age>=25的所有记录的ID和Name
                reader = sql.ReadTable("table1", new string[] { "ID", "Name" }, new string[] { "Age" }, new string[] { ">=" }, new string[] { "'25'" });
                while (reader.Read())
                {
                    //读取ID
                    Debug.Log(reader.GetInt32(reader.GetOrdinal("ID")));
                    //读取Name
                    Debug.Log(reader.GetString(reader.GetOrdinal("Name")));
                }

                //自定义SQL,删除数据表中所有Name="王五"的记录
                sql.ExecuteQuery("SELECT * FROM circuit");
        

        SqliteDataReader reader = sql.ReadFullTable("circuit");
        while (reader.Read())
        {
            //读取ID
            Debug.Log(reader.GetInt32(reader.GetOrdinal("id")));
            //读取Name
            Debug.Log(reader.GetString(reader.GetOrdinal("point1")));
            //读取Age
            Debug.Log(reader.GetString(reader.GetOrdinal("point2")));
            //读取Email
            Debug.Log(reader.GetString(reader.GetOrdinal("line")));
        }
        //关闭数据库连接
        sql.CloseConnection();
    }*/
}



